<template>
  <div class="page">
    <h2>社会少数与脆弱群体管理</h2>

    <div class="controls">
      <el-input v-model="q" placeholder="按姓名/档案号/问题搜索" clearable style="flex:1" @clear="onClear" />

      <el-select v-model="groupType" placeholder="群体类型" style="width:180px">
        <el-option label="全部" :value="''" />
        <el-option label="LGBTQ+" value="lgbtq" />
        <el-option label="移民/流动人口" value="migrant" />
        <el-option label="无家可归" value="homeless" />
        <el-option label="其他脆弱群体" value="other" />
      </el-select>

      <el-select v-model="riskFilter" placeholder="风险等级" style="width:140px">
        <el-option label="全部" :value="''" />
        <el-option label="低" value="low" />
        <el-option label="中" value="medium" />
        <el-option label="高" value="high" />
      </el-select>

      <div style="display:flex;gap:8px">
        <el-button type="primary" @click="openModal()">新增记录</el-button>
        <el-button @click="exportCSV">导出CSV</el-button>
      </div>
    </div>

    <el-table :data="filtered" stripe border style="width:100%;margin-top:12px" @selection-change="onSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="recordId" label="档案号" width="140" />
      <el-table-column prop="name" label="姓名" width="120" />
      <el-table-column prop="group" label="群体类型" width="160" />
      <el-table-column prop="risk" label="风险等级" width="120" />
      <el-table-column prop="issues" label="主要问题/需求" />
      <el-table-column prop="assigned" label="责任人" width="140" />
      <el-table-column prop="status" label="服务状态" width="120">
        <template #default="{ row }">
          <el-tag :type="row.status==='open' ? 'warning' : 'success'">{{ row.status==='open' ? '开启服务' : '已关闭' }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="220">
        <template #default="{ row }">
          <el-button size="small" @click="openModal(row.recordId)">编辑</el-button>
          <el-button size="small" @click="closeCase(row.recordId)" style="margin-left:8px">关闭</el-button>
          <el-button size="small" type="danger" @click="deleteOne(row.recordId)" style="margin-left:8px">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin-top:8px;display:flex;gap:8px;align-items:center">
      <el-button @click="batchClose">批量关闭服务</el-button>
      <el-button type="danger" @click="batchDelete">批量删除</el-button>
      <div style="flex:1"></div>
      <div class="muted">已选：{{ selectedIds.length }} 项</div>
    </div>

    <el-dialog :title="editingId ? '编辑记录' : '新增记录'" v-model="showModal" width="700px">
      <el-form :model="form" label-width="140px">
        <el-form-item label="档案号"><el-input v-model="form.recordId" /></el-form-item>
        <el-form-item label="姓名"><el-input v-model="form.name" /></el-form-item>
        <el-form-item label="群体类型">
          <el-select v-model="form.group" style="width:260px">
            <el-option label="LGBTQ+" value="LGBTQ+" />
            <el-option label="移民/流动人口" value="移民/流动人口" />
            <el-option label="无家可归" value="无家可归" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="风险等级"><el-select v-model="form.risk" style="width:160px"><el-option label="低" value="low" /><el-option label="中" value="medium" /><el-option label="高" value="high" /></el-select></el-form-item>
        <el-form-item label="主要问题/需求"><el-input v-model="form.issues" /></el-form-item>
        <el-form-item label="责任人"><el-input v-model="form.assigned" /></el-form-item>
        <el-form-item label="服务状态"><el-select v-model="form.status" style="width:160px"><el-option label="开启服务" value="open" /><el-option label="已关闭" value="closed" /></el-select></el-form-item>
        <el-form-item label="备注/资源链接"><el-input v-model="form.notes" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeModal">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

const DEFAULT_DATA = [
  { recordId: 'V001', name: '张某', group: 'LGBTQ+', risk: 'medium', issues: '心理咨询、社会支持', assigned: '李社工', status: 'open', notes: '本地支持组织链接' },
  { recordId: 'V002', name: '王某', group: '移民/流动人口', risk: 'high', issues: '语言障碍、法律援助', assigned: '王医生', status: 'open', notes: '' }
];

const data = ref([]);
const q = ref('');
const groupType = ref('');
const riskFilter = ref('');
const selectedRows = ref([]);
const selectedIds = ref([]);
const showModal = ref(false);
const editingId = ref(null);
const form = reactive({ recordId:'', name:'', group:'LGBTQ+', risk:'low', issues:'', assigned:'', status:'open', notes:'' });

onMounted(()=>{ load(); });
function load(){ data.value = JSON.parse(JSON.stringify(DEFAULT_DATA)); }

const filtered = computed(()=>{
  const qq = q.value.trim().toLowerCase();
  return data.value.filter(d=>{
    if(qq && !(d.name.toLowerCase().includes(qq) || String(d.recordId).toLowerCase().includes(qq) || (d.issues||'').toLowerCase().includes(qq))) return false;
    if(groupType.value){ const map = { lgbtq: 'LGBTQ+', migrant: '移民/流动人口', homeless: '无家可归', other: '其他' }; if(d.group !== map[groupType.value]) return false; }
    if(riskFilter.value && d.risk !== riskFilter.value) return false;
    return true;
  });
});

watch(selectedRows, v=>{ selectedIds.value = v.map(i=>i.recordId); });
function onSelectionChange(rows){ selectedRows.value = rows; }

function openModal(id){ editingId.value = id || null; if(id){ const it = data.value.find(x=>x.recordId===id); if(it) Object.assign(form, JSON.parse(JSON.stringify(it))); } else { Object.assign(form,{recordId:'',name:'',group:'LGBTQ+',risk:'low',issues:'',assigned:'',status:'open',notes:''}); } showModal.value = true; }
function closeModal(){ showModal.value = false; editingId.value = null; }
function save(){ if(!form.recordId || !form.name){ ElMessage.warning('档案号和姓名为必填项'); return; }
  if(editingId.value){ const it = data.value.find(x=>x.recordId===editingId.value); if(it) Object.assign(it, JSON.parse(JSON.stringify(form))); }
  else{ data.value.push(JSON.parse(JSON.stringify(form))); }
  showModal.value=false; ElMessage.success('保存成功'); }

function deleteOne(id){ ElMessageBox.confirm('确认删除该记录？','删除确认',{ confirmButtonText:'确定', cancelButtonText:'取消', type:'warning' })
  .then(()=>{ data.value = data.value.filter(x=>x.recordId!==id); ElMessage.success('已删除'); })
  .catch(()=>{});
}
function closeCase(id){ const it = data.value.find(x=>x.recordId===id); if(it){ it.status='closed'; ElMessage.success('已关闭'); } }
function batchClose(){ const ids = selectedIds.value; if(ids.length===0){ ElMessage.warning('请选择至少一项'); return; } data.value.forEach(d=>{ if(ids.includes(d.recordId)) d.status='closed'; }); ElMessage.success('操作完成'); }
function batchDelete(){ const ids = selectedIds.value; if(ids.length===0){ ElMessage.warning('请选择至少一项'); return; } ElMessageBox.confirm(`确认删除 ${ids.length} 条记录？`,'批量删除',{ confirmButtonText:'确定', cancelButtonText:'取消', type:'warning' })
  .then(()=>{ data.value = data.value.filter(d=>!ids.includes(d.recordId)); selectedIds.value = []; selectedRows.value = []; ElMessage.success('已删除'); })
  .catch(()=>{});
}

function exportCSV(){ const csv = [ ['recordId','name','group','risk','issues','assigned','status','notes'], ...data.value.map(d=>[d.recordId,d.name,d.group,d.risk,d.issues||'',d.assigned||'',d.status,d.notes||'']) ];
  const csvContent = csv.map(r=>r.map(cell=>`"${String(cell).replace(/"/g,'""')}"`).join(',')).join('\n');
  const blob = new Blob([csvContent],{type:'text/csv;charset=utf-8;'});
  const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href=url; a.download='vulnerable.csv'; document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(url);
}

function onClear(){}
</script>

<style scoped>
.page{font-family: Arial, "Microsoft YaHei", sans-serif; margin:10px;}
h2{margin-top:-10px}
.controls{display:flex;gap:8px;margin-bottom:12px;align-items:center}
.muted{color:#666;font-size:13px}
</style>